package com.ruoyi.functiontest.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.functiontest.mapper.EtcGantryTreeTestMapper;
import com.ruoyi.functiontest.domain.EtcGantryTreeTest;
import com.ruoyi.functiontest.service.IEtcGantryTreeTestService;
import com.ruoyi.function.mapper.EtcGantryTreeMapper;
import com.ruoyi.function.domain.EtcGantryTree;
import com.ruoyi.function.service.IEtcGantryTreeService;

/**
 * ETC门架区间数据测试Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-09-24
 */
@Service
public class EtcGantryTreeTestServiceImpl implements IEtcGantryTreeTestService 
{
    private static final Logger logger = LoggerFactory.getLogger(EtcGantryTreeTestServiceImpl.class);
    
    @Autowired
    private EtcGantryTreeTestMapper etcGantryTreeTestMapper;
    
    @Autowired
    private IEtcGantryTreeService etcGantryTreeService;

    /**
     * 查询ETC门架区间数据测试
     * 
     * @param id ETC门架区间数据测试主键
     * @return ETC门架区间数据测试
     */
    @Override
    public EtcGantryTreeTest selectEtcGantryTreeTestById(Long id)
    {
        return etcGantryTreeTestMapper.selectEtcGantryTreeTestById(id);
    }

    /**
     * 查询ETC门架区间数据测试列表
     * 
     * @param etcGantryTreeTest ETC门架区间数据测试
     * @return ETC门架区间数据测试
     */
    @Override
    public List<EtcGantryTreeTest> selectEtcGantryTreeTestList(EtcGantryTreeTest etcGantryTreeTest)
    {
        return etcGantryTreeTestMapper.selectEtcGantryTreeTestList(etcGantryTreeTest);
    }

    /**
     * 新增ETC门架区间数据测试
     * 
     * @param etcGantryTreeTest ETC门架区间数据测试
     * @return 结果
     */
    @Override
    public int insertEtcGantryTreeTest(EtcGantryTreeTest etcGantryTreeTest)
    {
        return etcGantryTreeTestMapper.insertEtcGantryTreeTest(etcGantryTreeTest);
    }

    /**
     * 修改ETC门架区间数据测试
     * 
     * @param etcGantryTreeTest ETC门架区间数据测试
     * @return 结果
     */
    @Override
    public int updateEtcGantryTreeTest(EtcGantryTreeTest etcGantryTreeTest)
    {
        return etcGantryTreeTestMapper.updateEtcGantryTreeTest(etcGantryTreeTest);
    }

    /**
     * 批量删除ETC门架区间数据测试
     * 
     * @param ids 需要删除的ETC门架区间数据测试主键
     * @return 结果
     */
    @Override
    public int deleteEtcGantryTreeTestByIds(Long[] ids)
    {
        return etcGantryTreeTestMapper.deleteEtcGantryTreeTestByIds(ids);
    }

    /**
     * 删除ETC门架区间数据测试信息
     * 
     * @param id ETC门架区间数据测试主键
     * @return 结果
     */
    @Override
    public int deleteEtcGantryTreeTestById(Long id)
    {
        return etcGantryTreeTestMapper.deleteEtcGantryTreeTestById(id);
    }

    /**
     * 是否存在子节点
     * 
     * @param id 节点ID
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public boolean hasChildById(Long id)
    {
        int result = etcGantryTreeTestMapper.hasChildById(id);
        return result > 0;
    }

    /**
     * 批量更新实测单位审核状态（review1字段设置为0）
     * 
     * @return 更新的记录数
     */
    @Override
    public int updateReview1ToZero()
    {
        return etcGantryTreeTestMapper.updateReview1ToZero();
    }

    /**
     * 校验所有数据的review1字段是否都为0
     * 
     * @return true 所有review1都为0，false 存在review1不为0的数据
     */
    @Override
    public boolean checkAllReview1IsZero()
    {
        int count = etcGantryTreeTestMapper.countReview1NotZero();
        return count == 0;
    }

    /**
     * 根据条件批量更新业主审核状态（review2字段设置为0）
     * 
     * @param etcGantryTreeTest 查询条件
     * @return 更新的记录数
     */
    @Override
    public int updateReview2ToZeroByCondition(EtcGantryTreeTest etcGantryTreeTest)
    {
        return etcGantryTreeTestMapper.updateReview2ToZeroByCondition(etcGantryTreeTest);
    }

    /**
     * 校验所有数据的review1和review2字段是否都不为空且都为0
     * 
     * @return true 所有review1和review2都不为空且为0，false 存在不符合条件的数据
     */
    @Override
    public boolean checkAllReview1AndReview2AreZero()
    {
        int count = etcGantryTreeTestMapper.countReview1OrReview2NotZero();
        return count == 0;
    }

    /**
     * 批量更新中心审核状态（review3字段设置为0）
     * 
     * @return 更新的记录数
     */
    @Override
    public int updateReview3ToZero()
    {
        return etcGantryTreeTestMapper.updateReview3ToZero();
    }

    /**
     * 导入ETC门架区间数据测试数据
     * 简化导入逻辑：直接按照Excel原始格式导入，通过id和parentid来确定数据
     * 
     * @param etcGantryTreeTestList ETC门架区间数据测试列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @return 结果
     */
    @Override
    public String importEtcGantryTreeTest(List<EtcGantryTreeTest> etcGantryTreeTestList, Boolean isUpdateSupport)
    {
        if (etcGantryTreeTestList == null || etcGantryTreeTestList.isEmpty())
        {
            return "导入数据不能为空！";
        }
        
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        
        // 简化导入逻辑：直接按照Excel原始格式导入
        for (EtcGantryTreeTest data : etcGantryTreeTestList)
        {
            try
            {
                // 基本数据验证
                if (data.getRoadName() == null) {
                    data.setRoadName("");
                }
                
                // 通过id和parentid来确定数据
                EtcGantryTreeTest existingNode = null;
                
                // 使用新的方法通过id和parentid组合来精确匹配数据
                EtcGantryTreeTest query = new EtcGantryTreeTest();
                query.setId(data.getId());
                query.setParentId(data.getParentId());
                query.setLongitude(data.getLongitude());
                query.setLatitude(data.getLatitude());
                query.setGantryLocation(data.getGantryLocation());
                
                List<EtcGantryTreeTest> existingNodes = etcGantryTreeTestMapper.selectEtcGantryTreeTestByIdAndParentId(query);
                if (existingNodes != null && !existingNodes.isEmpty()) {
                    existingNode = existingNodes.get(0);
                }
                
                if (existingNode != null) {
                    // 已存在节点，如果支持更新则更新
                    if (isUpdateSupport) {
                        existingNode.setRoadName(data.getRoadName());
                        existingNode.setEtcCode(data.getEtcCode());
                        existingNode.setNodeName(data.getNodeName());
                        existingNode.setLongitude(data.getLongitude());
                        existingNode.setLatitude(data.getLatitude());
                        existingNode.setGantryLocation(data.getGantryLocation());
                        existingNode.setRemark(data.getRemark());
                        existingNode.setParentId(data.getParentId());
                        
                        etcGantryTreeTestMapper.updateEtcGantryTreeTest(existingNode);
                        successNum++;
                    } else {
                        // 不支持更新，跳过此条数据
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + ". 数据已存在，跳过: " + data.getRoadName() + "-" + data.getEtcCode() + "-" + data.getGantryLocation());
                    }
                } else {
                    // 不存在节点，创建新节点
                    EtcGantryTreeTest newNode = new EtcGantryTreeTest();
                    newNode.setId(data.getId()); // 使用Excel中的id值
                    newNode.setRoadName(data.getRoadName());
                    newNode.setEtcCode(data.getEtcCode());
                    newNode.setNodeName(data.getNodeName());
                    newNode.setLongitude(data.getLongitude());
                    newNode.setLatitude(data.getLatitude());
                    newNode.setGantryLocation(data.getGantryLocation());
                    newNode.setRemark(data.getRemark());
                    newNode.setParentId(data.getParentId());
                    
                    etcGantryTreeTestMapper.insertEtcGantryTreeTest(newNode);
                    successNum++;
                }
                
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + ". 导入失败：";
                if (data.getRoadName() != null)
                {
                    msg += "路段名称：" + data.getRoadName();
                }
                if (data.getEtcCode() != null)
                {
                    msg += "，ETC序号：" + data.getEtcCode();
                }
                failureMsg.append(msg + e.getMessage());
            }
        }
        
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            return failureMsg.toString();
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据已导入到系统。");
            return successMsg.toString();
        }
    }
    
    /**
     * 检查所有数据的review1、review2和review3是否为0，并将数据同步到正式表
     * 
     * @return 同步结果信息
     */
    @Override
    @Transactional
    public String syncDataToEtcGantryTree()
    {
        // 1. 检查所有数据的review1、review2和review3是否都为0
        int count = etcGantryTreeTestMapper.countReview1OrReview2OrReview3NotZero();
        if (count > 0) {
            throw new RuntimeException("存在未完成审核的数据，请确保所有数据的review1、review2和review3字段都为0");
        }
        
        // 2. 查询所有审核通过的数据
        EtcGantryTreeTest query = new EtcGantryTreeTest();
        List<EtcGantryTreeTest> testDataList = etcGantryTreeTestMapper.selectEtcGantryTreeTestList(query);
        
        if (testDataList == null || testDataList.isEmpty()) {
            return "同步失败：没有找到可同步的数据";
        }
        
        int successNum = 0;
        int failureNum = 0;
        StringBuilder failureMsg = new StringBuilder();
        
        // 3. 遍历数据，同步到正式表
        for (EtcGantryTreeTest testData : testDataList) {
            try {
                // 创建正式表对象
                EtcGantryTree etcGantryTree = new EtcGantryTree();
                etcGantryTree.setId(testData.getId());
                etcGantryTree.setParentId(testData.getParentId());
                etcGantryTree.setRoadName(testData.getRoadName());
                etcGantryTree.setEtcCode(testData.getEtcCode());
                etcGantryTree.setNodeName(testData.getNodeName());
                etcGantryTree.setLongitude(testData.getLongitude());
                etcGantryTree.setLatitude(testData.getLatitude());
                etcGantryTree.setGantryLocation(testData.getGantryLocation());
                etcGantryTree.setRemark(testData.getRemark());
                
                // 检查正式表中是否已存在相同id的数据
                EtcGantryTree existingData = etcGantryTreeService.selectEtcGantryTreeById(testData.getId());
                
                if (existingData != null) {
                    // 已存在，更新数据
                    etcGantryTreeService.updateEtcGantryTree(etcGantryTree);
                } else {
                    // 不存在，插入数据
                    etcGantryTreeService.insertEtcGantryTree(etcGantryTree);
                }
                
                successNum++;
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + ". 同步失败：";
                if (testData.getRoadName() != null) {
                    msg += "路段名称：" + testData.getRoadName();
                }
                if (testData.getEtcCode() != null) {
                    msg += "，ETC序号：" + testData.getEtcCode();
                }
                failureMsg.append(msg + "，错误：" + e.getMessage());
                logger.error("同步数据失败：", e);
            }
        }
        
        if (failureNum > 0) {
            failureMsg.insert(0, "同步完成，但部分数据同步失败！成功同步 " + successNum + " 条，失败 " + failureNum + " 条，错误如下：");
            return failureMsg.toString();
        } else {
            return "恭喜您，数据同步成功！共同步 " + successNum + " 条数据到正式表。";
        }
    }

}
